package com.alfy.sbdemo.websocketdemo.demo1;

import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import java.util.List;
import java.util.Map;

/**
 * 认证配置
 */
public class AuthConfigurator extends ServerEndpointConfig.Configurator {

    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {

        boolean isAuthenticated = false;

        // 通过 HTTP Headers 进行认证
        List<String> authHeaders = request.getHeaders().get("Authorization");
        if (authHeaders != null && !authHeaders.isEmpty()) {
            String authToken = authHeaders.get(0);
            isAuthenticated = isValidToken(authToken);
        }

        // 如果 HTTP Headers 认证失败，则通过 URL 参数进行认证
        if (!isAuthenticated) {
            Map<String, List<String>> parameters = request.getParameterMap();
            List<String> tokens = parameters.get("token");
            if (tokens != null && !tokens.isEmpty()) {
                isAuthenticated = isValidToken(tokens.get(0));
            }
        }

        // 如果两种方式都未通过认证，则拒绝握手
        if (!isAuthenticated) {
            throw new RuntimeException("Authentication failed");
        }else {
            System.out.println("Authentication successfully");
        }
        super.modifyHandshake(sec, request, response);
    }

    // 认证方法
    private boolean isValidToken(String token) {
        // 在这里实现令牌验证逻辑
        // 例如，检查令牌是否存在于数据库中或者是否具有特定格式
        return "valid-token".equals(token); // 示例验证
    }

}
